﻿Imports System.Data
Imports System.IO
Imports VSModel
Imports Cls_Common
Imports SecurityService

Partial Class Control_MSDS_UploadVi
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
#Region " PRIVARTE SUB AND FUNCTION"
    Sub ShowData()
        Using data As New VSEntities
            Dim p As MSDSOriginal = (From q In data.MSDSOriginals Where q.Id = hidID.Value Select q).SingleOrDefault
            If Not p Is Nothing Then
                txtItemcode.Text = IIf(IsNothing(p.ItemCode) = True, "", p.ItemCode)
                hidItemCode.Value = txtItemcode.Text
                txtItemname.Text = IIf(IsNothing(p.ItemName) = True, "", p.ItemName)
                hidVendorCode.Value = IIf(IsNothing(p.VendorCode) = True, "", p.VendorCode)
                txtVendorname.Text = IIf(IsNothing(p.Vendorname) = True, "", p.Vendorname)
                txtOriginal.Text = IIf(IsNothing(p.Original) = True, "", p.Original)

                Dim _originalFile As String = IIf(IsNothing(p.TraslateFile) = True, "", p.TraslateFile)
                hidOldFile.Value = _originalFile
                If _originalFile.IndexOf("___") > -1 Then
                    Dim _indexLast = _originalFile.LastIndexOf("___") + 3
                    Dim fileName As String = _originalFile.Substring(_indexLast, _originalFile.Length - _indexLast)
                    txtFileUploadName.Text = fileName
                End If
            End If
        End Using
    End Sub
#End Region
#Region "EVENT CONTROL-PAGE"
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Me.EnableViewState = False
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
            If Not Request.QueryString("Id").ToString.Equals("0") Then
                hidID.Value = Request.QueryString("Id")
                ShowData()
            End If
        End If
    End Sub

    Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
        Using data As New VSEntities
            Try
                Dim p As MSDSOriginal
                p = (From q In data.MSDSOriginals Where q.Id = hidID.Value).FirstOrDefault
                If Not p Is Nothing Then

                    Dim _FileUploadPath As String = ""
                    Dim _PathSave As String = ""
                    Dim _error As String = ""
                    If flDocument.HasFile Then
                        Dim fileExtension As String = If(flDocument.FileName.IndexOf(".") <> -1, flDocument.FileName.Split(".")(1), "")
                        If Not (fileExtension = "pdf" Or fileExtension = "PDF") Then
                            Excute_Javascript("AlertboxRedirect('Vui lòng chọn đúng file pdf để upload','../../Page/MSDS/UploadVi.aspx?Id=" + hidID.Value + "');", Me.Page, True)
                            Exit Sub
                        End If

                        'To save every file with different name
                        Dim randamName As String = DateTime.Now.ToFileTime().ToString()
                        Dim relativePath As String = Server.MapPath("~") & "\Uploads\MSDS\"
                        'Complete path of the file.
                        _FileUploadPath = (relativePath & randamName) + flDocument.FileName
                        _PathSave = MainDomain & randamName & flDocument.FileName
                        Try
                            ' tiến hành upload file lên server
                            flDocument.SaveAs(_FileUploadPath)
                        Catch ex As Exception
                            _FileUploadPath = ""
                            _PathSave = ""
                            _error = " Upload file fail !"
                        Finally
                        End Try
                    Else
                        Excute_Javascript("AlertboxRedirect('Vui lòng chọn đúng file dịch để upload','../../Page/MSDS/UploadVi.aspx?Id=" + hidID.Value + "');", Me.Page, True)
                        ShowData()
                        Exit Sub
                    End If
                    With p
                        .TraslateFile = _PathSave
                        .Modifier = Session("UserName")
                        .Modified = Now.Date
                    End With
                    data.SaveChanges()
                    '' Check file old exists --> Delete
                    Try
                        If File.Exists(hidOldFile.Value) Then
                            File.Delete(hidOldFile.Value)
                        End If
                    Catch ex As Exception
                    End Try

                    Insert_App_Log("Update  MSDSOriginal - upload vi:" & txtItemname.Text.Trim & "", Function_Name.MSDSOriginal, Audit_Type.Edit, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                    Excute_Javascript("AlertboxRedirect('Lưu dữ liệu thành công." & _error & "','../../Page/MSDS/List.aspx');", Me.Page, True)
                End If
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Cập nhật thất bại.');", Me.Page, True)
            Finally
                GC.Collect()
            End Try
        End Using
    End Sub

    Protected Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
        Response.Redirect("List.aspx")
    End Sub
#End Region
End Class
